package com.wuliu.common.utils;

import cn.hutool.core.util.XmlUtil;
import com.alibaba.fastjson.JSONObject;
import com.wuliu.common.core.domain.ApiResult;
import com.wuliu.common.core.domain.SendSmsInfoDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 云点短信服务
 */
@Component
public class YDMsgUtils {
    protected static Logger logger = LoggerFactory.getLogger(YDMsgUtils.class);

    /**
     * 运单短信发送
     *
     * @param sendSmsInfo
     * @return
     */
    public static Map<String, Object> sendMsg(String signName, SendSmsInfoDto sendSmsInfo) {
        try {
            String content = "【" + signName + "】" + sendSmsInfo.getContent();
            String urlString = URLEncoder.encode(content, "utf-8");
            String reqParams = sendSmsInfo.getSendUrl() + "/sms?action=" + sendSmsInfo.getAction() + "&userid=" + sendSmsInfo.getUserId() + "&account=" + sendSmsInfo.getAccount() + "&password="
                    + sendSmsInfo.getPassword() + "&mobile=" + sendSmsInfo.getMobile() + "&content=" + urlString;
            if (StringUtils.isNotEmpty(sendSmsInfo.getExtNo()))
                reqParams = reqParams + "&extno=" + sendSmsInfo.getExtNo();
            if (StringUtils.isNotEmpty(sendSmsInfo.getSendTime()))
                reqParams = reqParams + "&sendTime=" + sendSmsInfo.getSendTime();
            String result = HttpKit.post(reqParams, "");
            Map<String, Object> sendRet = new HashMap<>();
            Map<String, Object> resultMap = XmlUtil.xmlToMap(result);
            logger.error("发送短信返回结果:" + JSONObject.toJSONString(resultMap));
            if (StringUtils.isNotEmpty(resultMap)) {
                sendRet.put("status", resultMap.get("returnstatus") + "");
                sendRet.put("message", resultMap.get("message") + "");
                sendRet.put("msgId", resultMap.get("taskID") + "");
                sendRet.put("successCounts", resultMap.get("successCounts") + "");
                sendRet.put("remainpoint", resultMap.get("remainpoint") + "");
            }
            return sendRet;
        } catch (Exception e) {
            logger.error("发送短信错误:{}", e.getMessage());
            return null;
        }
    }
}
